<?php
/**
 * @author Jerry
 * 
 */

class Dispatch
{
	/**
	 * 路由
	 */
	private $_route;
	
	private $_controller;
	
	private $_action;
	
	private $_params;
	
	private $_param;
	
	public function __construct(Router $route)
	{
		$this->_route 		= $route;
		$this->_action 		= $this->_route->getAction();
		$this->_controller 	= $this->_route->getController();
		$this->_params 		= $this->_route->getParams();
		$this->_param 		= $this->_route->getParam();
		
		$request_uri = $_SERVER['REQUEST_URI'];
		$request_uri = explode('/', trim($request_uri, '/'));
		$appdir = count($request_uri) > 1 ? Arr::get($request_uri, 0) : 'app';
		define('APP_CHANEL', $appdir);
		define('APP_DIR', SYS_ROOT . $appdir . DS);
		define('TEMPLATE_DIR', APP_DIR . 'views' . DS);
		
		$_ctl_file = APP_DIR . 'controller' .DS. $this->_controller . '.php';
		$_model_file = APP_DIR . 'model' .DS. $this->_controller . '.php';
		$_view_file = APP_DIR . 'views' .DS. $this->_action . '.html';
		if (!file_exists($_ctl_file))
		{
			throw new Exception("你请求的控制器【{$_ctl_file}】文件不存在！");
		}
		require_once($_ctl_file);
		$controller = ucfirst(strtolower($this->_controller)).'Controller';
		$action = 'action' . ucfirst(strtolower($this->_action));
		$_ctl = new $controller;
		$_ctl->setController($this->_controller);
		if (!method_exists($_ctl, $action))
		{
			throw new Exception("你请求的控制器【{$controller}】方法【{$action}】不存在！");
		}
		$_ctl->setAction($this->_action);
		$_ctl->setParams($this->_params);
		$_ctl->setParam($this->_param);
		$_ctl->$action();		
	}
}
?>